import os
# os.environ['CUDA_VISIBLE_DEVICES'] = '1,0'
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from threading import Lock

# Parameters and DataLoaders
input_size = 5
output_size = 2
print('R{0} -> R{1}'.format(input_size, output_size, ))

batch_size = 29
data_size = 98
print('batch size', batch_size)
print('data size', data_size)

# device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")  # nn.DataParallel(model): RuntimeError: module must have its parameters and buffers on device cuda:0 (device_ids[0]) but found one of them on device: cuda:1
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")


class RandomDataset(Dataset):

    def __init__(self, size, length):
        self.len = length
        self.data = torch.randn(length, size)

    def __getitem__(self, index):
        return self.data[index]

    def __len__(self):
        return self.len


rand_loader = DataLoader(dataset=RandomDataset(input_size, data_size),
                         batch_size=batch_size, shuffle=True)


class Model(nn.Module):
    # Our model

    def __init__(self, input_size, output_size, lock):
        super(Model, self).__init__()
        self.fc = nn.Linear(input_size, output_size)
        self.lock = lock

    def forward(self, input):
        output = self.fc(input)
        with self.lock:
            print("\tIn Model: input size", input.size(), "output size", output.size())

        return output


lock = Lock()
model = Model(input_size, output_size, lock)
if torch.cuda.device_count() > 1:
  print("Let's use", torch.cuda.device_count(), "GPUs!")
  # dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
  model = nn.DataParallel(model)

model.to(device)

for data in rand_loader:
    input = data.to(device)
    output = model(input)
    with lock:
        print("Outside: input size", input.size(), "output_size", output.size())
